# roles.py

import random

ROLES = {
    "蛇喰梦子": {
        "description": "如果你的前三张牌均选择不要，你的点数+6。",
        "skill": lambda p, g: {"bonus": 6 if all(c not in p['selected_cards'] for c in p['cards'][:3]) else 0},
        "image_file": "蛇喰梦子.png"
    },
    "早乙女芽亚里": {
        "description": "你翻开的最后一张牌若小于5，则视为K（13点）。",
        "skill": lambda p, g: {"bonus": replace_last_card_with_k(p)},
        "image_file": "早乙女芽亚里.png"
    },
    "豆生田枫": {
        "description": "你的人头牌（J、Q、K）点数+2。",
        "skill": lambda p, g: {"bonus": calculate_face_card_bonus(p)},
        "image_file": "豆生田枫.png"
    },
    "户隐雪见": {
        "description": "如果你选出的三张牌中有两张点数或花色相同，则总点数+5。",
        "skill": lambda p, g: {"bonus": calculate_snow_skill(p)},
        "image_file": "户隐雪见.png"
    },
    "佐渡魅久良": {
        "description": "如果你选择的牌点数均在7以下，结算时分数加倍。",
        "skill": lambda p, g: {"bonus": double_score_if_all_below_seven(p)},
        "image_file": "佐渡魅久良.png"
    },
    "生志摩妄": {
        "description": "你的每张牌的点数有几率乘以2或者变为0点（4/6不变，1/6乘以2，1/6变为0）。",
        "skill": lambda p, g: calculate_shouzhi_mo_wang_skill(p),
        "image_file": "生志摩妄.png"
    },
    "下月売奥理": {
        "description": "你可以看到所有6张牌，但若结算不是前两名，也要接受惩罚（惩罚是局外的）。",
        "skill": lambda p, g: {"bonus": 0},
        "image_file": "下月売奥理.png"
    },
    "骨喰米拉斯拉瓦": {
        "description": "当你只选择1张牌时，你的分数x3。",
        "skill": lambda p, g: {"bonus": calculate_honebane_miraslava_skill(p)},
        "image_file": "骨喰米拉斯拉瓦.png"
    },
    "桃喰绮罗莉": {
        "description": "每轮游戏一次，你可以选择重新开始你的回合。",
        "skill": lambda p, g: {"bonus": 0},
        "image_file": "桃喰绮罗莉.png"
    },
    "铃井凉太": {
        "description": "你得分最低的牌视为6点。",
        "skill": lambda p, g: {"bonus": handle_ryota_suzui_skill(p)},
        "image_file": "铃井凉太.png"
    },
    "桃喰莉莉香": {
        "description": "在你的回合结束后，丢弃你点数最低的牌，再随机抽一张牌。",
        "skill": lambda p, g: {"bonus": 0},
        "image_file": "桃喰莉莉香.png"
    },
    "西洞院百合子": {
        "description": "你的奇数牌点数翻倍，偶数牌变为减去相应点数（总得分允许为负数）。",
        "skill": lambda p, g: {"bonus": handle_yuriko_nishidoin_skill(p)},
        "image_file": "西洞院百合子.png"
    },
    "花手毬葛笼": {
        "description": "如果你的三张牌是按顺序排列的A-7（例：236），则你的分数视为40分。",
        "skill": lambda p, g: {"bonus": calculate_hanamaru_tsuzura_skill(p)},
        "image_file": "花手毬葛笼.png"
    },
    "皇伊月": {
        "description": "在你拿到花牌（J,Q,K）时，如果你选择不要，你可以在后续的牌中多拿一张牌。本技能一轮限触发一次。",
        "skill": lambda p, g: {"bonus": 0},
        "image_file": "皇伊月.png"
    },
    "五十岚清华": {
        "description": "游戏结束时，你可以选择一位其他玩家，使其总分-6。",
        "skill": lambda p, g: {"bonus": 0},
        "skill_type": "interactive_post_game",
        "skill_effect": {"action": "modify_score", "num_targets": 1, "score_modifier": -6},
        "image_file": "五十岚清华.png"
    },
    "壬生臣葵": {
        "description": "如果你弃掉的牌里包含全部四种花色，你的得分变为这四张牌（每种花色取最大的一张）的点数和。",
        "skill": lambda p, g: {"bonus": calculate_mibuomi_aoi_skill(p)},
        "image_file": "壬生臣葵.png"
    },
    "等等喰定乐乃": {
        "description": "游戏结束时，你可以选择两位其他玩家，交换他们的最终分数。",
        "skill": lambda p, g: {"bonus": 0},
        "skill_type": "interactive_post_game",
        "skill_effect": {"action": "swap_scores", "num_targets": 2},
        "image_file": "等等喰定乐乃.png"
    }
}

def get_card_value(card):
    rank_values = {'A':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':11,'Q':12,'K':13}
    return rank_values[card['rank']]

def calculate_shouzhi_mo_wang_skill(player):
    base_score = sum(get_card_value(c) for c in player['selected_cards'])
    skill_score, log = 0, []
    for card in player['selected_cards']:
        value = get_card_value(card)
        card_name = f"{card['suit']}{card['rank']}"
        rand = random.randint(1, 6)
        if rand == 1:
            new_value = value * 2
            skill_score += new_value
            log.append(f"【{card_name}】点数变为 {new_value} (x2)！")
        elif rand == 2:
            new_value = 0
            skill_score += new_value
            log.append(f"【{card_name}】点数变为 0！")
        else:
            skill_score += value
            log.append(f"【{card_name}】点数不变。")
    return {"bonus": skill_score - base_score, "log": log}

def calculate_mibuomi_aoi_skill(player):
    cards_to_check = player['discarded_cards']
    present_suits = {c['suit'] for c in cards_to_check}
    if len(present_suits) < 4: return 0
    highest_cards_by_suit = {}
    for card in cards_to_check:
        suit = card['suit']
        value = get_card_value(card)
        if suit not in highest_cards_by_suit or value > get_card_value(highest_cards_by_suit[suit]):
            highest_cards_by_suit[suit] = card
    skill_score = sum(get_card_value(c) for c in highest_cards_by_suit.values())
    base_score = sum(get_card_value(c) for c in player['selected_cards'])
    return skill_score - base_score

def calculate_hanamaru_tsuzura_skill(player):
    sc = player['selected_cards']
    if len(sc) != 3: return 0
    values = sorted([get_card_value(c) for c in sc])
    if any(v > 7 for v in values): return 0
    if len(set(values)) != 3: return 0
    return 40 - sum(values)

def replace_last_card_with_k(player):
    if player['selected_cards']:
        last_card = player['selected_cards'][-1]
        if get_card_value(last_card) < 5:
            return 13 - get_card_value(last_card)
    return 0

def calculate_face_card_bonus(player):
    return sum(2 for c in player['selected_cards'] if c['rank'] in ['J', 'Q', 'K'])

def calculate_snow_skill(player):
    sc = player['selected_cards']
    if len(sc) < 2: return 0
    ranks = [c['rank'] for c in sc]
    suits = [c['suit'] for c in sc]
    if len(ranks) != len(set(ranks)) or len(suits) != len(set(suits)):
        return 5
    return 0

def double_score_if_all_below_seven(player):
    sc = player['selected_cards']
    if not sc or not all(get_card_value(c) <= 7 for c in sc): return 0
    return sum(get_card_value(c) for c in sc)

def calculate_honebane_miraslava_skill(player):
    if len(player['selected_cards']) == 1:
        return sum(get_card_value(c) for c in player['selected_cards']) * 2
    return 0

def handle_ryota_suzui_skill(player):
    sc = player['selected_cards']
    if not sc: return 0
    min_value = min(get_card_value(c) for c in sc)
    return max(0, 6 - min_value)

def handle_yuriko_nishidoin_skill(player):
    base_score = sum(get_card_value(c) for c in player['selected_cards'])
    skill_score = sum((get_card_value(c) * 2 if get_card_value(c) % 2 == 1 else -get_card_value(c)) for c in player['selected_cards'])
    return skill_score - base_score

